package io.osw.modules.sys.controller;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

import io.osw.common.validator.ValidatorUtils;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.VerticalAlignment;
import jxl.write.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import io.osw.modules.sys.entity.TblBudgetUseEntity;
import io.osw.modules.sys.service.TblBudgetUseService;
import io.osw.common.utils.PageUtils;
import io.osw.common.utils.R;

import javax.servlet.http.HttpServletResponse;


/**
 * 预算使用表
 *
 * @author guxiaoguang
 * @email xuebai864627555@gmail.com
 * @date 2019-01-10 22:58:35
 */
@RestController
@RequestMapping("sys/tblbudgetuse")
public class TblBudgetUseController extends AbstractController{
    @Autowired
    private TblBudgetUseService tblBudgetUseService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:tblbudgetuse:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = tblBudgetUseService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{bgUserId}")
    @RequiresPermissions("sys:tblbudgetuse:info")
    public R info(@PathVariable("bgUserId") Long bgUserId){
        TblBudgetUseEntity tblBudgetUse = tblBudgetUseService.selectById(bgUserId);

        return R.ok().put("tblBudgetUse", tblBudgetUse);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:tblbudgetuse:save")
    public R save(@RequestBody TblBudgetUseEntity tblBudgetUse){
        tblBudgetUse.setCreateTime(new Date());
        tblBudgetUse.setCreateBy(getUser().getUserId());
        tblBudgetUseService.insert(tblBudgetUse);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:tblbudgetuse:update")
    public R update(@RequestBody TblBudgetUseEntity tblBudgetUse){
        ValidatorUtils.validateEntity(tblBudgetUse);
        tblBudgetUse.setUpdateTime(new Date());
        tblBudgetUse.setUpdateBy(getUser().getUserId());
        tblBudgetUseService.updateAllColumnById(tblBudgetUse);//全部更新
        
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:tblbudgetuse:delete")
    public R delete(@RequestBody Long[] bgUserIds){
        tblBudgetUseService.deleteBatchIds(Arrays.asList(bgUserIds));

        return R.ok();
    }

    /*
     * 导出数据
     * */
    @RequestMapping(value = "/exportLog", method = RequestMethod.GET)
    public void importExcel(@RequestParam String ids, HttpServletResponse response) throws Exception {
        List list = new ArrayList(Arrays.asList(ids.split("-")));
        StringBuilder sbd = new StringBuilder();
        sbd.append("预算执行情况表");
        String title = sbd.toString();
        response.setContentType("application/force-download");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.addHeader("Content-Type", "application/vnd.ms-excel; charset=utf-8");
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("Content-Disposition", new StringBuilder("attachment;filename=").append(URLEncoder.encode(title, "UTF-8")).append(".xlsx").toString());
        try (OutputStream out = response.getOutputStream()) {
            WritableWorkbook workbook = Workbook.createWorkbook(out);
            WritableSheet sheet = workbook.createSheet("预算执行情况表", 0);
            //设置列宽
            sheet.setColumnView(0, 20);//名字
            sheet.setColumnView(1, 16);//手机号
            sheet.setColumnView(2, 20);//地址
            sheet.setColumnView(3, 16);//生日
            sheet.getSettings().setVerticalFreeze(1);

            //初始化标题
            WritableFont titleWft = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false);
            titleWft.setColour(Colour.BROWN);
            WritableCellFormat titleFmt = new WritableCellFormat(titleWft);
            titleFmt.setBackground(Colour.GRAY_25);
            titleFmt.setAlignment(Alignment.CENTRE);
            titleFmt.setVerticalAlignment(VerticalAlignment.CENTRE);
            WritableCellFormat titleFmt1 = new WritableCellFormat();
            titleFmt1.setAlignment(Alignment.LEFT);
            WritableCellFormat titleFmt2 = new WritableCellFormat();
            titleFmt2.setAlignment(Alignment.RIGHT);
            WritableCellFormat priceFmt = new WritableCellFormat(new NumberFormat("#0.00"));

            //写标题
            sheet.addCell(new Label(0, 0, "姓名", titleFmt));
            sheet.addCell(new Label(1, 0, "手机号", titleFmt));
            sheet.addCell(new Label(2, 0, "地址", titleFmt));
            sheet.addCell(new Label(3, 0, "生日", titleFmt));

            SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
            List<TblBudgetUseEntity>  tblBudgetUseEntity= tblBudgetUseService.selectBatchIds(list);
            int row = 1;
            for (TblBudgetUseEntity log : tblBudgetUseEntity) {
                //区间名字
                if (StringUtils.isBlank(log.getPeriodName()) || log.getPeriodName().equals("0")) {
                    sheet.addCell(new Label(0, row, "无", titleFmt1));
                } else {
                    sheet.addCell(new Label(0, row, log.getPeriodName()));
                }
                //
                if (StringUtils.isBlank(log.getPeriodDate()) || log.getPeriodDate().equals("0")) {
                    sheet.addCell(new Label(1, row, "无", titleFmt2));
                } else {
                    sheet.addCell(new Label(1, row, log.getPeriodDate()));
                }
                if (StringUtils.isBlank(log.getAttribute1()) || log.getAttribute1().equals("0")) {
                    sheet.addCell(new Label(2, row, "无", titleFmt2));
                } else {
                    sheet.addCell(new Label(2, row, log.getAttribute1()));
                }
                if (log.getCreateTime() == null) {
                    sheet.addCell(new Label(3, row, "无", titleFmt2));
                } else {
                    sheet.addCell(new Label(3, row, sdf.format(log.getCreateTime())));
                }
                ++row;
            }
            workbook.write();
            workbook.close();
        }
    }

}
